package v1

import (
	"RoccBlog/api"
	"RoccBlog/global"
	"github.com/gin-gonic/gin"
	"time"
)

// SSEController 注册消息接收事件
type SSEController struct {
	api.BaseController
}

func (c *SSEController) RegisterController(engine *gin.RouterGroup) {
	//信息事件
	engine.GET("/message", c.SubscribeMessage)
}

func init() {
	global.RegisterController(&SSEController{})
}

// SubscribeMessage
// @Tags 订阅消息
// @Summary 订阅消息
// @Produce  json
// @Param name query string false ""
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Success 200 {object} api.Result "成功"
// @Router /message [get]
func (c *SSEController) SubscribeMessage(ctx *gin.Context) {
	//设置问文本事件流
	ctx.Header("Content-Type", "text/event-stream")
	//不进行缓存
	ctx.Header("Cache-Control", "no-cache")
	//设置为长期存活
	ctx.Header("Connection", "keep-alive")

	//获取上下文关闭通知管道
	closeNotify := ctx.Request.Context().Done()

	timer := time.NewTicker(time.Second)
	for {
		select {
		case <-closeNotify:
			//通道关闭
			break
		case <-timer.C:
			ctx.SSEvent("message", time.Now().Format("2006-01-02 15:04:05"))
			ctx.Writer.Flush()
			break
		}
	}
}
